package com.crazymakercircle.imServer.redisDao.impl;



import com.crazymakercircle.imServer.distributed.ImWorker;
import com.crazymakercircle.imServer.redisDao.SessionRemoteDAO;
import com.crazymakercircle.imServer.server.DistrubutedSession;
import com.crazymakercircle.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * 保存会话到 redis
 * create by 尼恩 @ 疯狂创客圈
 **/
@Repository("SessionRemoteRedisImpl")
public class SessionRemoteRedisImpl implements SessionRemoteDAO {

    //redis 缓存的前缀
    public static final String REDIS_PREFIX = "DistrubutedSession:sessionid:";
    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;
    private static final long CASHE_LONG =60 * 4 ;//4小时


    @Override
    public void save(final DistrubutedSession s) {
        String key = REDIS_PREFIX + s.getSessionId();
        String value = JsonUtil.pojoToJson(s);
        redisTemplate.opsForValue().set(key, value, CASHE_LONG, TimeUnit.MINUTES);

    }


    @Override
    public DistrubutedSession get(final String sessionid) {
        String key = REDIS_PREFIX + sessionid;
        String value = (String) redisTemplate.opsForValue().get(key);

        if (!StringUtils.isEmpty(value)) {
            return JsonUtil.jsonToObject(value, DistrubutedSession.class);
        }
        return null;
    }


    @Override
    public void casheRemoteSession(String uid, String sessionId) {
        //制作一个远程session,保存到分布式缓存
        DistrubutedSession rs = new DistrubutedSession(
                sessionId, uid, ImWorker.getInst().getId()
        );
        this.save(rs);

    }

    @Override
    public void removeRemote(String uid, String sessionId) {
        String key = REDIS_PREFIX + sessionId;
        redisTemplate.delete(key);
    }
}